import axios from 'axios'
import {Message} from "element-ui";

axios.interceptors.response.use(resp => {
    if (resp.status == 200 && resp.data && resp.data.code == 500) {
        if (resp.data.msg) {
            Message.error({message: resp.data.msg});
            return;
        }
    }
    if (resp.data.msg) {
        Message.success({message: resp.data.msg});
    }
    return resp.data;
},error => {
    if (error.response) {
        if (error.response.status) {
            if (error.response.status == 404 || error.response.status == 504) {
                Message.error({message: '服务被吃了（´Д`）'});
            } else if (error.response.status == 403) {
                Message.error({message: '权限不足'});
            } else if (error.response.status == 401) {
                Message.error({message: '用户未认证'});
            } else {
                Message.error({message: '未知错误'});
            }
        }
    }
    return;
})


export const getRequest = (url,params) =>{
    return axios({
        method : 'get',
        url : url,
        data : params
    })
}

export const postRequest = (url,params) =>{
    return axios({
        method : 'post',
        url : url,
        data : params
    })
}

export const postKeyValueRequest = (url,params) =>{
    return axios({
        method : 'post',
        url : url,
        data : params,
        transformRequest : [
            function (data) {
                let result = '';
                for (let i in data) {
                    result += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&';
                }
                return result;
            }
        ],
        header : {
            'Content-Type' : 'application/x-www-form-urlencoded'
        }
    })
}

export const putRequest = (url,params) =>{
    return axios({
        method : 'put',
        url : url,
        data : params
    })
}

export const deleteRequest = (url,params) =>{
    return axios({
        method : 'delete',
        url : url,
        data : params
    })
}